//
//  ASUserModel.m
//  AvatarShow
//
//  Created by xunruiIOS on 2021/4/27.
//

#import "ASUserModel.h"

@implementation ASUserModel

- (void)encodeWithCoder:(NSCoder *)coder
{
    unsigned int count = 0;
    Ivar * ivars = class_copyIvarList([self class], &count);
    for (int i = 0; i < count; i++) {
        Ivar ivar = ivars[i];
        const char * name = ivar_getName(ivar);
        NSString * key = [NSString stringWithUTF8String:name];
        //kvc 获取属性的值
        id value = [self valueForKey:key];
        
        //归档!!
        [coder encodeObject:value forKey:key];
    }
    free(ivars);
}

- (instancetype)initWithCoder:(NSCoder *)coder
{
    self = [super init];
    if (self) {
        unsigned int count = 0;
        Ivar * ivars = class_copyIvarList([self class], &count);
        for (int i = 0; i < count; i++) {
            Ivar ivar = ivars[i];
            const char * name = ivar_getName(ivar);
            NSString * key = [NSString stringWithUTF8String:name];
            //解档
            id value = [coder decodeObjectForKey:key];
            //设置到属性上面  kvc
            [self setValue:value forKey:key];
        }
        free(ivars);
    }
    return self;
}

- (NSString *)sexStr{
    NSString *str = @"未设置";
    if (self.sex.intValue == 1) {
        str = @"男";
    }else if(self.sex.intValue == 2){
        str = @"女";
    }
    return str;
}

@end

@implementation ASUserManager

+(instancetype)sharedManger {
    static dispatch_once_t onceToken;
    static ASUserManager *instance;
    dispatch_once(&onceToken, ^{
        instance = [[ASUserManager alloc] init];
        [instance unArchiverUserInfo];
    });
    return instance;
}

-(void)archiverUserInfo:(ASUserModel *)userInfo {
    NSData *userData = [NSKeyedArchiver archivedDataWithRootObject:userInfo];
    [[NSUserDefaults standardUserDefaults]setObject:userData forKey:@"UserManagerUserData"];
    [[NSUserDefaults standardUserDefaults] synchronize];

}

-(void)unArchiverUserInfo {
    NSData *userData = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserManagerUserData"];
    if ([userData isKindOfClass:[NSData class]]) {
        ASUserModel *userInfo = [NSKeyedUnarchiver unarchiveObjectWithData:userData];
        if (userInfo) {
            self.userInfo = userInfo;
            self.isLogin = YES;
            if (userInfo.hasYouKe.intValue == 1) {
                self.hasYouKe = YES;
            }else{
                self.hasYouKe = NO;
            }
        }
    }
}

- (void)removeUserData{
    self.isLogin = NO;
    self.hasYouKe = NO;
    self.userInfo = [ASUserModel new];
    [[NSUserDefaults standardUserDefaults]setObject:@"" forKey:@"UserManagerUserData"];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

@end
